using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneLoadTrigger : MonoBehaviour
{
    [SerializeField, Header("需要加载的场景数组")] private SceneField[] _scenesToLoad;
    [SerializeField, Header("需要卸载的场景数组")] private SceneField[] _scenesToUnload;
    private GameObject _player; // 玩家对象

    private void Awake()
    {
        _player = GameObject.FindGameObjectWithTag("Player"); // 查找并赋值玩家对象
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject == _player) // 碰撞体为玩家时
        {
            LoadScenes(); 
            UnloadScenes(); 
        }
    }

    // 加载场景
    private void LoadScenes()
    {
        for (int i = 0; i < _scenesToLoad.Length; i++)
        {
            bool isSceneLoaded = false;
            for (int j = 0; j < SceneManager.sceneCount; j++)
            {
                Scene loadedScene = SceneManager.GetSceneAt(j);
                if (loadedScene.name == _scenesToLoad[i].SceneName)
                {
                    isSceneLoaded = true;
                    break;
                }
            }
            if (!isSceneLoaded)
            {
                SceneManager.LoadSceneAsync(_scenesToLoad[i].SceneName, LoadSceneMode.Additive); // 异步加载需要加载的场景
            }
        }
    }

    // 卸载场景
    private void UnloadScenes()
    {
        for (int i = 0; i < _scenesToUnload.Length; i++)
        {
            for (int j = 0; j < SceneManager.sceneCount; j++)
            {
                Scene loadedScene = SceneManager.GetSceneAt(j);
                if (loadedScene.name == _scenesToUnload[i].SceneName)
                {
                    SceneManager.UnloadSceneAsync(_scenesToUnload[i].SceneName); // 异步卸载需要卸载的场景
                }
            }
        }
    }
}
